package com.androway.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import android.util.Pair;

public class Query
{
	public static List<?> search(Class<?> clazz, List<?> elements, Pair<String, ?>... entries)
	{
		List<Object> newList = new ArrayList<Object>();
		Method method;
		Object value;
		boolean toAdd = true;

		for (Object obj : elements)
		{
			toAdd = true;
			for (Pair<String, ?> entry : entries)
			{
				try
				{
					method = clazz.getMethod("get" + entry.first.substring(0, 1).toUpperCase() + entry.first.substring(1, entry.first.length()));
					value = method.invoke(obj);
					if (!value.equals(entry.second))
					{
						toAdd = false;
						break;
					}
				}
				catch (NoSuchMethodException e)
				{
					e.printStackTrace();
					return null;
				}
				catch (IllegalArgumentException e)
				{
					e.printStackTrace();
					return null;
				}
				catch (IllegalAccessException e)
				{
					e.printStackTrace();
					return null;
				}
				catch (InvocationTargetException e)
				{
					e.printStackTrace();
					return null;
				}
			}
			if (toAdd)
				newList.add(obj);
		}
		return newList;
	}

	public static List<?> filter(Class<?> clazz, List<?> elements, Pair<String, String>... entries)
	{
		List<Object> newList = new ArrayList<Object>();
		Method method;
		String value;
		boolean toAdd = true;

		for (Object obj : elements)
		{
			toAdd = true;
			for (Pair<String, String> entry : entries)
			{
				try
				{
					method = clazz.getMethod("get" + entry.first.substring(0, 1).toUpperCase() + entry.first.substring(1, entry.first.length()));
					value = (String) method.invoke(obj);
					if (!value.substring(0, entry.second.length()).equals(entry.second))
					{
						toAdd = false;
						break;
					}
				}
				catch (NoSuchMethodException e)
				{
					e.printStackTrace();
					return null;
				}
				catch (IllegalArgumentException e)
				{
					e.printStackTrace();
					return null;
				}
				catch (IllegalAccessException e)
				{
					e.printStackTrace();
					return null;
				}
				catch (InvocationTargetException e)
				{
					e.printStackTrace();
					return null;
				}
			}
			if (toAdd)
				newList.add(obj);
		}
		return newList;
	}
}
